import { createRouter, createWebHistory } from "vue-router";
//@ts-ignore
import nprogress from "nprogress";

const router = createRouter({
  history: createWebHistory(),
  routes: [
    {
      path: "/home",
      component: () => import("@/views/Home.vue"),
      name: "home",
      meta: {
        title: "首页",
      },
    },
    {
      path: "/",
      redirect: "/home",
      children: [],
    },
    {
      path: "/user",
      redirect: "/user/center",
      children: [
        {
          path: "/user/center",
          component: () => import("@/views/UserCenter.vue"),
          name: "userCenter",
          meta: {
            title: "用户中心",
          },
        },
      ],
    },
    {
      path: "/article",
      name: "article",
      component: () => import("@/views/Article.vue"),
      meta: {
        title: "游戏资讯",
      },
    },
    {
      path: "/community",
      name: "community",
      component: () => import("@/views/CommunityArticle.vue"),
      meta: {
        title: "帖子",
      },
    },
    {
      path: "/message",
      name: "message",
      component: () => import("@/views/Message.vue"),
      redirect: "/message/chat",
      children: [
        {
          path: "/message/chat",
          name: "chat",
          component: () => import("@/components/Chat.vue"),
        },
      ],
    },
  ],
});

router.beforeEach((to, from, next) => {
  const token = localStorage.getItem("token");
  const paths = ["/home", "/", "/article", "/community"];
  nprogress.start();
  if (paths.includes(to.path)) {
    return next();
  }
  if (token) {
    return next();
  }
  return next(from.path);
});

router.afterEach((to, _from, _failure) => {
  document.title = `电竞荣耀 - ${to.meta.title}`;
  nprogress.done();
});

export default router;
